package cz.data.gateway.model.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import cz.data.gateway.model.entity.GatewayRoute;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Data
@Slf4j
public class GatewayRouteVo {
    @ApiModelProperty(value = "记录主键")
    private String id;
    @ApiModelProperty(value = "路由ID")
    private String routeId;
    @ApiModelProperty(value = "路由描述")
    private String description;
    @ApiModelProperty(value = "路由状态")
    private String status;
    @ApiModelProperty(value = "负载上游路径")
    private String uri;
    @ApiModelProperty(value = "路由优先级")
    private Integer orders;
    @ApiModelProperty(value = "创建人")
    private String createBy;
    @ApiModelProperty(value = "创建时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;
    @ApiModelProperty(value = "更新人")
    private String updateBy;
    @ApiModelProperty(value = "更新时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;
    @ApiModelProperty(value = "路由过滤规则")
    private List<FilterDefinitionDto> filters = new ArrayList<>();
    @ApiModelProperty(value = "路由断言规则")
    private List<PredicateDefinitionDto> predicates = new ArrayList<>();

    public GatewayRouteVo() {}
    public GatewayRouteVo(GatewayRoute gatewayRoute) {
        this.id = gatewayRoute.getId();
        this.routeId = gatewayRoute.getRouteId();
        this.uri = gatewayRoute.getUri();
        this.description = gatewayRoute.getDescription();
        this.status = gatewayRoute.getStatus();
        this.orders = gatewayRoute.getOrders();
        this.createBy = gatewayRoute.getCreateBy();
        this.createTime = gatewayRoute.getCreateTime();
        this.updateBy = gatewayRoute.getUpdateBy();
        this.updateTime = gatewayRoute.getUpdateTime();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.filters = objectMapper.readValue(gatewayRoute.getFilters(), new TypeReference<List<FilterDefinitionDto>>() {
            });
            this.predicates = objectMapper.readValue(gatewayRoute.getPredicates(), new TypeReference<List<PredicateDefinitionDto>>() {
            });
        } catch (IOException e) {
            log.error("网关路由对象转换失败", e);
        }
    }
}
